﻿using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.Core;
using Kiiro.Model;
using Microsoft.SharePoint.Utilities;
using Kiiro.SiteDefinition.MasterPage;

namespace Kiiro.SiteDefinition.ControlTemplates
{
    public partial class MyWorkItem : KiiroUserControl
    {
        private BasePage Base
        {
            get { return ( BasePage ) Page; }
        }

        private Work work;
        public Work Work
        {
            get { return work; }
            set { work = value; }
        }

        private bool isLastItem = false;
        public bool IsLastItem
        {
            get { return isLastItem; }
            set { isLastItem = value; }
        }

        public double HoursPerDay
        {
            get { return SetupModel.GetHoursPerDay ( Base.SiteCollectionId, Base.ServerRelativeUrl ); }
        }

        protected override void OnPreRender ( EventArgs e )
        {
            base.OnPreRender ( e );

            if (Work != null)
            {
                if (IsLastItem)
                {
                    tblRowTitle.CssClass += " borderless";
                    tblRowDetail.CssClass += " borderless";
                }

                if ( IsPortal )
                {
                    tblCellTitle.CssClass = tblCellTitle.CssClass.Replace ( "title", "portal-item" );
                }

                tblCellTitle.CssClass += " " + Work.WorkItemType.ToString().ToLower();
                lnkTitle.Text = SPHelpers.ConvertHtmlToKiiroSafeText(Work.Title) ?? string.Empty;
                lblDueDate.Text = FormattingHelpers.DateTimeToStringOrDashes(Work.EndDate);

                string type = Work.WorkItemType == WorkType.Issue ? Constants.ProjectFileUrls.IssueDisplay : Constants.ProjectFileUrls.TaskDisplay;
                if (SPHelpers.IsProject(Base.SiteCollectionId, Base.ServerRelativeUrl))
                {
                    lnkTitle.NavigateUrl = String.Format("{0}{1}?id={2}", Base.ServerRelativeUrl, type, Work.Id);
                }
                else
                {
                    hidProjectSRU.Value = SPHelpers.GetServerRelativeWebUrl(work.SiteCollectionId, work.ServerRelativeUrl);
                    if (string.IsNullOrEmpty(hidProjectSRU.Value))
                    {
                        tblCellProject.Visible = true;
                        lnkTitle.NavigateUrl = String.Format("{0}{1}?id={2}", SPHelpers.GetServerRelativeWebUrl(work.SiteCollectionId, work.ServerRelativeUrl), type, Work.Id);
                        lnkProject.Text = "Unknown Project";
                        lnkProject.NavigateUrl = string.Empty;
                    }
                    else
                    {
                        tblCellProject.Visible = true;
                        lnkTitle.NavigateUrl = String.Format("{0}{1}?id={2}", SPHelpers.GetServerRelativeWebUrl(work.SiteCollectionId, work.ServerRelativeUrl), type, Work.Id);
                        string projectTitle = ProjectsModel.GetByServerRelativeWebUrl(work.SiteCollectionId, hidProjectSRU.Value).Title;
                        lnkProject.Text = projectTitle;
                        lnkProject.NavigateUrl = hidProjectSRU.Value;
                    }
                }

                hidWorkItemId.Value = Work.Id.ToString();

                txtStatusMessage.Text = SPHelpers.ConvertHtmlToKiiroSafeText(Work.StatusNote) ?? string.Empty;
                lblAssignedTime.Text = FormattingHelpers.ConvertFromMinutes(Work.AssignedWork, Base.KiiroMaster.V2Header.Project.TimeMetric, HoursPerDay).ToString("F1");

                if (Work.AttachmentList.Count > 0)
                {
                    imgAttachment.Visible = true;
                    imgAttachment.AlternateText = string.Format("This {0} has {1} attachment{2}",
                        Work.WorkItemType.ToString().ToLower(), Work.AttachmentList.Count, Work.AttachmentList.Count > 1 ? "s" : "");
                }

                if (Work.IsHighPriority)
                {
                    imgHighPriority.Visible = true;
                    imgHighPriority.AlternateText = "This issue is high priority";
                }

                if (Work.Status == StatusType.Closed || Work.Status == StatusType.Completed)
                {
                    imgCompleted.Visible = true;
                    imgCompleted.AlternateText = Work.Status == StatusType.Completed ? "This task is completed" : "This issue is completed";
                }

                if (Base.KiiroMaster.V2Header.Project != null)
                {
                    lblTimeUnit.Text = Base.KiiroMaster.V2Header.Project.TimeMetric.ToString();
                }

                dlTask.Visible = Work.WorkItemType == WorkType.Task;
                dlIssue.Visible = Work.WorkItemType == WorkType.Issue;

                litPercentComplete.Text = !float.IsNaN(Work.PercentageComplete) && !float.IsInfinity(Work.PercentageComplete)
                    ? Work.PercentageComplete.ToString() : "0";

                rblIssueStatus.SelectedValue = ((byte)Work.Status).ToString();

                lnkUpdateTime.Visible = PermissionsModel.CanTeamMemberUpdateWork(Base.CurrentUser, Work, Base.SiteCollectionId, Base.ServerRelativeUrl);
            }
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/CONTROLTEMPLATES/Kiiro/MyWorkItem.ascx.cs $
 * 
 * 15    1/13/10 1:10p Camerons
 * 
 * 14    12/23/09 3:27p Stefanf
 * 
 * 13    27/10/09 12:00p Shafia
 * took out the PermissionsModel.GetGlobalPermissionBitsForCurrentUser (
 * Work, Base.CurrentUser, Base.SiteCollectionId, Base.ServerRelativeUrl
 * ); from OnPreRender
 * 
 * 12    10/26/09 9:25a Adamw
 * 
 * 11    10/23/09 6:11p Adamw
 * Case 348
 * 
 * 10    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 9     30/09/09 9:35a Shafia
 * 
 * 8     14/09/09 9:17a Shafia
 * added "uknown project" title if project is not returned so it won't
 * blow up.
 * 
 * 7     17/08/09 10:50a Camerons
 * Shafi:
 *  Tuesday Aug 11: Changed lnkTitle.NavigateUrl to check if work is
 * displayed on portal recreate the link to correct project.
 *  
 * Shafi
 *  Friday Aug 14,2009:
 *  Changes:
 *       = If the page is WorkOnAllProjects on portal then i fix the link
 * for the title to direct it to the project Display Work page
 *       = Added hiprojectSRU to be able to get the project server
 * relative url when at portal level to save work using ajax
 * 
 ************************************************************************/